﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MyKnights.Entity;
using MyKnights.UI;
using MyKnights.Styles;

namespace MyKnights.UI
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window, IMainWindow
    {
        private readonly CenterHandler _handler;

        public MainWindow()
        {
            InitializeComponent();
            UIKElsie.Height = Const.UI.UIKHeight;
            UIKEirlys.Height = Const.UI.UIKHeight;
            UIKDai.Height = Const.UI.UIKHeight;
            UIKKaour.Height = Const.UI.UIKHeight;
            Loaded += MainWindow_Loaded;
            Closed += MainWindow_Closed;
            _handler = new CenterHandler();
        }

        private void MainWindow_Closed(object sender, EventArgs e)
        {
            _handler?.OnAppClose();
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            _handler.Initialize(this);
            CollectionViewSource logCvs = (CollectionViewSource)FindResource("LogViewSource");
            logCvs.Source = _handler.ChangeLogManager.Logs;
        }

        private void MainGrid_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DragMove();
        }

        private void ButtonClose_OnClick(object sender, RoutedEventArgs e)
        {
            if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
            {
                Close();
            }
            else
            {
                WindowState = WindowState.Minimized;
            }
        }

        private void CBProfiles_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                Profile pfi = e.AddedItems[0] as Profile;
                if (pfi == null) return;
                _handler.ChangeProfile(pfi);
            }
        }

        private void OnTopicChanged(object sender, Topic fromTopic, Topic toTopic)
        {
            UIKnight uik = sender as UIKnight;
            if (uik == null) return;
            _handler.UpdateKnightTopic(uik.Knight, fromTopic, toTopic);
        }

        private void MIAdd_OnClick(object sender, RoutedEventArgs e)
        {
            ProfileEditWindow tew = new ProfileEditWindow { Owner = this };
            tew.InitializeShow(ProfileEditWindow.Operation.Add, _handler);
        }

        private void MIEdit_OnClick(object sender, RoutedEventArgs e)
        {
            ProfileEditWindow tew = new ProfileEditWindow { Owner = this };
            tew.InitializeShow(ProfileEditWindow.Operation.Edit, _handler);
        }

        private void MIDelete_OnClick(object sender, RoutedEventArgs e)
        {
            ProfileEditWindow tew = new ProfileEditWindow { Owner = this };
            tew.InitializeShow(ProfileEditWindow.Operation.Delete, _handler);
        }

        private void Tips_OnClick(object sender, RoutedEventArgs e)
        {
            TipsWindow tw = new TipsWindow { Owner = this };
            tw.ShowDialog();
        }

        private void MIAbout_OnClick(object sender, RoutedEventArgs e)
        {
            AboutWindow aw = new AboutWindow { Owner = this };
            aw.ShowDialog();
        }

        private void ButtonPin_OnClick(object sender, RoutedEventArgs e)
        {
            Topmost = !Topmost;
            UpdatePinButtonStatus();
            _handler.UserData.AppStatus.MainWindowStatus.Topmost = Topmost;
        }

        private void MITopicExport_OnClick(object sender, RoutedEventArgs e)
        {
            var ret = MessageBox.Show(this, $"导出后,可以修改和使用自定义(文件位置:data\\{Const.Path.TopicsFileName}),删除后恢复内置模版\n是否继续导出?", "提示",
                MessageBoxButton.YesNo);
            if (MessageBoxResult.Yes == ret)
            {
                _handler.Knights.SaveToFile();
            }
        }

        private void ButtonClearLog_OnClick(object sender, RoutedEventArgs e)
        {
            _handler?.ClearLog();
        }

        private void ButtonLogView_OnClick(object sender, RoutedEventArgs e)
        {
            if (GridLog.Visibility.Equals(Visibility.Visible))
            {
                GridLog.Visibility = Visibility.Hidden;
                BorderLog.Visibility = Visibility.Hidden;
                _handler.UserData.AppStatus.GridLogVisible = false;
            }
            else
            {
                GridLog.Visibility = Visibility.Visible;
                BorderLog.Visibility = Visibility.Visible;
                _handler.UserData.AppStatus.GridLogVisible = true;
            }
        }

        private void LogViewSource_OnFilter(object sender, FilterEventArgs e)
        {
            string kw = TBSearch.Text.Trim();
            if (string.IsNullOrWhiteSpace(kw)) e.Accepted = true;
            else
            {
                ChangeLog cl = e.Item as ChangeLog;
                if (cl != null)
                {
                    e.Accepted = cl.DisplayText.Contains(kw);
                }
            }
        }

        private void TBSearch_OnTextChanged(object sender, TextChangedEventArgs e)
        {
            RefreshLogs();
        }

        private void UpdatePinButtonStatus()
        {
            ButtonPin.Visibility = Topmost ? Visibility.Collapsed : Visibility.Visible;
            ButtonUnpin.Visibility = !Topmost ? Visibility.Collapsed : Visibility.Visible;
        }

        #region IMainWindow
        public void ApplyAppStatus(AppStatus appStatus)
        {
            if (TUtil.TCommond.DoubleIsZero(appStatus.MainWindowStatus.Left) &&
                TUtil.TCommond.DoubleIsZero(appStatus.MainWindowStatus.Top))
            {

            }
            else
            {
                this.Left = appStatus.MainWindowStatus.Left;
                this.Top = appStatus.MainWindowStatus.Top;
            }

            GridLog.Visibility = appStatus.GridLogVisible ? Visibility.Visible : Visibility.Hidden;
            BorderLog.Visibility = appStatus.GridLogVisible ? Visibility.Visible : Visibility.Hidden;
            Topmost = appStatus.MainWindowStatus.Topmost;
            UpdatePinButtonStatus();
            appStatus.LastStartupTime = DateTime.Now;
        }
        public void InitProfile(UserData userData)
        {
            CBProfiles.Items.Clear();
            foreach (Profile pfi in userData.Profiles)
            {
                CBProfiles.Items.Add(pfi);
            }
            //触发Changed事件:CBProfiles_OnSelectionChanged
            CBProfiles.SelectedItem = _handler.CurrentProfile;
        }

        public void LoadTopics(Knights kinghts)
        {
            UIKElsie.LoadTopics(kinghts.Elsie);
            UIKEirlys.LoadTopics(kinghts.Eirlys);
            UIKDai.LoadTopics(kinghts.Dai);
            UIKKaour.LoadTopics(kinghts.Kaour);
        }

        public void LoadKnightVisibility(KnightVisibility knightVisibility)
        {
            double uiksHeight = .0;
            if (knightVisibility.Eirlys)
            {
                uiksHeight += Const.UI.UIKHeight;
            }
            if (knightVisibility.Dai)
            {
                uiksHeight += Const.UI.UIKHeight;
            }
            if (knightVisibility.Elsie)
            {
                uiksHeight += Const.UI.UIKHeight;
            }
            if (knightVisibility.Kaour)
            {
                uiksHeight += Const.UI.UIKHeight;
            }

            UIKElsie.Visibility = knightVisibility.Elsie ? Visibility.Visible : Visibility.Collapsed;
            UIKEirlys.Visibility = knightVisibility.Eirlys ? Visibility.Visible : Visibility.Collapsed;
            UIKDai.Visibility = knightVisibility.Dai ? Visibility.Visible : Visibility.Collapsed;
            UIKKaour.Visibility = knightVisibility.Kaour ? Visibility.Visible : Visibility.Collapsed;

            this.Height = uiksHeight + 26 + 4;
        }

        public void RefreshLogs()
        {
            CollectionViewSource logCvs = (CollectionViewSource)FindResource("LogViewSource");
            logCvs?.View.Refresh();
            if (LbLog.Items.Count > 0)
            {
                LbLog.SelectedItem = LbLog.Items[0];
                LbLog.ScrollIntoView(LbLog.Items[0]);
            }
        }
        #endregion

        private void MainWindow_OnLocationChanged(object sender, EventArgs e)
        {
            if (_handler != null && _handler.Initialized)
            {
                _handler.UserData.AppStatus.MainWindowStatus.Left = this.Left;
                _handler.UserData.AppStatus.MainWindowStatus.Top = this.Top;
            }
        }
    }
}
